package com.shadow.baiqun.delegate.room.tilting;

import android.device.ScanDevice;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;

import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.delegate.room.adapter.ClaimGoodsAdapter;
import com.shadow.baiqun.event.ScanInfoEvent;
import com.shadow.baiqun.view.TableHeadView;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;
import com.shadow.ui.recycler.BaseDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author zhangyu
 * @date 2018/7/23
 * 取货列表
 */

public class ClaimGoodsDelegate extends RxShadowDelegate {
    private static final String TASK_ID = "taskId";


    public static ClaimGoodsDelegate create(String taskId) {
        final ClaimGoodsDelegate contentDelegate = new ClaimGoodsDelegate();
        final Bundle bundle = new Bundle();
        bundle.putString(TASK_ID, taskId);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.lv_title)
    TableHeadView mHeadView;
    private String mTaskId;
    private boolean isRequesting = false;
    private ClaimGoodsAdapter mClaimGoodsAdapter;
    private String mBordCode;

    private ScanDevice mScanDevice;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mTaskId = bundle.getString(TASK_ID);
        }
        mScanDevice = new ScanDevice();
//        广播输出
        mScanDevice.setOutScanMode(0);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_claim_goods;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("取货列表");
            mToolbar.inflateMenu(R.menu.scan);
            mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    int i = item.getItemId();
                    if (i == R.id.menu_scan) {
                        scan();
                    }
                    return true;
                }
            });

        }
        List<String> list = new ArrayList<>();
        list.add("条码号");
        list.add("库位");
        list.add("状态");
        mHeadView.setHeaders(list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(BaseDecoration.create(getContext().getResources()
                .getColor(R.color.color_white_light_gray), 1));
        mClaimGoodsAdapter = new ClaimGoodsAdapter(getContext(),
                R.layout.item_claim_goods_task, null);
        mClaimGoodsAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
        if (mClaimGoodsAdapter.getEmptyView() != null) {
            mClaimGoodsAdapter.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refresh();
                }
            });
        }
        mRecyclerView.setAdapter(mClaimGoodsAdapter);
    }

    private void scan() {
        if (!mScanDevice.isScanOpened()) {
            mScanDevice.openScan();
        }
        mScanDevice.startScan();
        //TODO 扫描
        //      doClaim("000000032715");
    }

    private void doClaim(String code) {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/turnbag/qhAction")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        int code = new ResultConverter().getCode(response);
                        if (code == 0) {
                            ToastUtils.showToast(getContext(), "不是翻包零件!");
                        } else if (code == 1) {
                            ToastUtils.showToast(getContext(), "取货成功!");
                            refresh();
                        } else {
                            ToastUtils.showToast(getContext(), "系统错误!");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        ToastUtils.showToast(getContext(), msg);
                    }
                })
                .params("tabCode", code)
                .build()
                .unRestGet());
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        refresh();
    }

    private void refresh() {
        if (!isRequesting) {
            isRequesting = true;
            mClaimGoodsAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
            requestData();
        }

    }

    private void requestData() {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/turnbag/turnBagDetail")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mClaimGoodsAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        ClaimGoodsDataConverter converter = new ClaimGoodsDataConverter();
                        converter.setJsonData(response);
                        mClaimGoodsAdapter.setNewData(converter.convert());
                        isRequesting = false;
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mClaimGoodsAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        isRequesting = false;
                    }
                })
                .params("taskid", mTaskId)
                .params("datatype", 1)
//                .params("pageNum", 1)
//                .params("pageSize", 30)
                .build()
                .unRestGet());
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        refresh();
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void scanEvent(ScanInfoEvent event) {
        doClaim(event.mInfo);
    }
}
